//弹出与关闭
let reservation = document.querySelector('.reservation-operation')
let popUp = document.querySelector('.pop-up-reservation')
let container = document.querySelector('.container')
let noReservation = document.querySelector('.no-reservation')
let seats = document.querySelectorAll('.seat')



popUp.addEventListener('click', function (e) {
    reservation.style.visibility = 'visible'
    e.preventDefault()
})

function closeReversation() {
    reservation.style.visibility = 'hidden'
}

function homePage() {
    location.href = '/public/seat'
}

//页面加载时判断有没有预约  有预约就显示预约信息
document.addEventListener('DOMContentLoaded', judge())

setInterval(() => {
    judge()
}, 2000);
// 判断有没有预约
function judge() {
    axios.get('/my/reservation', {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.status === 0) {
            container.style.display = 'flex'
            noReservation.style.display = 'none'
            seats.forEach((seat, index) => {
                if (index + 1 === res.data.data.seat_id) {
                    seat.classList.add('fa-wheelchair');
                }
            })
            //把信息更新到页面
            let reservationDate = document.querySelector('.reservation-content-inner')
            //日期格式化以yyyy-mm-dd hh:mm格式返回
            let date = new Date(res.data.data.reservation_date)
            date = date.toLocaleString()
            let seatID = res.data.data.seat_id
            let time = res.data.data.reservation_time
            let reservationStatus = res.data.data.reservation_status
            let reservationStatusText = '申请中...'
            if (reservationStatus === 1) {
                reservationStatusText = '申请中'
            } else if (reservationStatus === 2) {
                reservationStatusText = `<p style='color:red'>被拒绝<p>`
            } else if (reservationStatus === 3) {
                reservationStatusText = `<p style='color:green'>已接受<p>`
            }
            reservationDate.innerHTML = `
            <td>${seatID}</td>
            <td>${date}</td>
            <td>${time}</td>
            <td>${reservationStatusText}</td>
            <td><a href='javascript:;' onclick="cancleReservation()">取消预约</a></td>`

            axios.get('/my/userinfo', {
                headers: {
                    authorization: localStorage.getItem('token')
                }
            }).then(res => {
                if (res.data.status !== 0) {
                    return console.log(res.data.message);
                } else {
                    let nickname = res.data.data.nickname
                    let studentId = res.data.data.studentId
                    let Class = res.data.data.class
                    let major = res.data.data.major
                    let reservationInfoContent = document.querySelector('.reservation-info-content')
                    reservationInfoContent.innerHTML = `
                    <p>姓名：${nickname}</p>
                    <p>学号：${studentId}</p>
                    <p>专业: ${major}</p>
                    <p>班级：${Class}</p>
                    <p>座位号：${seatID}</p>
                    <p>预约时间：${date}</p>
                    <p>预约时长：${time}</p>
                `
                }
            })
        } else {
            seats.forEach(seat => {
                seat.onclick = function (e) {
                    if (e.target.classList.contains('fa-user-times')) {
                        return;
                    }
                    else if (e.target.classList.contains('fa-user')) {
                        return;
                    }
                    else {
                        seats.forEach((seat) => {
                            seat.classList.remove('fa-user-o');
                        })
                        e.target.classList.add('fa-user-o');
                    }
                }
            })
        }
    }).catch(err => {
        console.log(err);
    });
}

//根据id获取预约信息（判断是否已经预约）
function getreservationbyid() {
    let id = document.querySelector('#seatID').value;
    axios.post('/seat/reservationbyid', { id }, {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.data[0].status !== 0) {
            swal("预约失败", "该座位已经被预约", "error");
        } else {
            insertreservation()
        }
    }).catch(error => {
        console.error(error);
        swal("预约失败", `${error}`, "error")
    });
}

//点击按钮
function reserve() {
    getreservationbyid()
}

//插入事件

function insertreservation() {
    let seat_id = document.querySelector('#seatID').value;
    let reservation_date = document.querySelector('#reserveTime').value;
    let reservation_time = parseInt(document.querySelector('#reserveDuration').value);
    //不为空
    if (!reservation_date || !reservation_time) {
        return swal('预约失败', '请填写完整信息', 'error')
    }
    axios.get('/my/reservation', {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.status === 0) {
            return swal('申请预约失败', '您已经预约了座位', 'error')
        } else {
            axios.post('/seat/insertreservation', {
                seat_id,
                reservation_date,
                reservation_time,
            }, {
                headers: {
                    Authorization: localStorage.getItem('token')
                }
            }).then(res => {
                if (res.data.status === 0) {
                    swal('申请预约成功', '即将刷新', 'success')
                    //关闭弹窗
                    setTimeout(() => {
                        location.reload()
                    }, 1000);
                } else {
                    swal('申请预约失败', `${res.data.message}`, 'error')
                }
            }).catch(err => {
                console.log(err);
            });
        }
    }).catch(err => {
        console.log(err);
    });
}

//取消预约
function cancleReservation() {
    axios.get('/my/reservation', {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.status === 0) {
            axios.post('/my/cancelreservation', {
                id: res.data.data.seat_id
            }, {
                headers: {
                    Authorization: localStorage.getItem('token')
                }

            }).then(res => {
                if (res.data.status === 0) {
                    swal("取消预约成功", "即将刷新", "success");
                    setTimeout(function () {
                        location.reload()
                    }, 1000);
                } else {
                    swal("取消预约失败", `${res.data.message}`, "error");
                }
            }).catch(err => {
                console.log(err);
            });
        }
    }).catch(err => {
        console.log(err);
    });
}